package com.photoeditor.demo.model.image.frame;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ThumbnailUtils;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.widget.ImageView;

import com.common.base.ComponentContext;
import com.common.base.utils.DeviceUtils;

import java.io.File;
import java.io.FileFilter;
import java.lang.ref.WeakReference;
import java.util.LinkedHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Pattern;


public class FrameIconManager {
    private final int widthOrHeight;

//    private static HashMap<String, Drawable> mDrawales;

    /**
     * 用于保存核心数目
     */
    private static int CPU_CORE_NUMBER = 1;

    static{
        try {
            File dir = new File("/sys/devices/system/cpu/");
            if ( dir != null ) {
                File[] files = dir.listFiles(new FileFilter() {
                    @Override
                    public boolean accept(File pathname) {
                        if(Pattern.matches("cpu[0-9]", pathname.getName())) {
                            return true;
                        }
                        return false;
                    }
                });
                CPU_CORE_NUMBER =  files.length;
            }

        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 线程池
     */
    protected ExecutorService mThreadPool;

    /**
     * 缓存图片的Map
     */
    private static LinkedHashMap<String, Bitmap> mThumbnailBitmaps;

    //缓存图片的个数
    private static final int CACHE_SIZE = 64;

    private static final int MSG_END_RUNABLE = 200;

    private static final String FRAME_ID="frame_id";

    private Handler mHandler = new Handler(Looper.getMainLooper()){
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what == MSG_END_RUNABLE){
                HandlerWithDatabean databean = (HandlerWithDatabean) msg.obj;
//                CollageBackgroundView frameViewTag = (CollageBackgroundView)databean.frameView.getTag();
                if(databean.mBitmap != null && !databean.mBitmap.isRecycled()&&databean.frameView.getTag().equals(databean.position)){//确保是同一个 且一切正常
                    databean.frameView.setBackgroundDrawable(new BitmapDrawable(databean.mBitmap));
                    mThumbnailBitmaps.put(FRAME_ID+databean.mSrcframeID, databean.mBitmap);
                }
            }
        };
    };

    private static final ThreadFactory sThreadFactory = new ThreadFactory() {
        private final AtomicInteger mCount = new AtomicInteger(1);

        public Thread newThread(Runnable r) {
            return new Thread(r, "EmojiIconTask #" + mCount.getAndIncrement());
        }
    };

    public FrameIconManager(Context context){
        widthOrHeight = DeviceUtils.dip2px(context, 69);
        mThreadPool = Executors.newFixedThreadPool(CPU_CORE_NUMBER + 1, sThreadFactory);
        if(mThumbnailBitmaps == null) {
            mThumbnailBitmaps = new LinkedHashMap<String, Bitmap>(CACHE_SIZE, 0.5f, true) {

                private static final long serialVersionUID = 1L;

                @Override
                protected boolean removeEldestEntry(Entry<String, Bitmap> eldest) {
                    if (size() > CACHE_SIZE) {
                        return true;
                    }
                    return super.removeEldestEntry(eldest);
                }
            };
        }
    }

    /**
     * 加载Icon,从缓存中取,去不到再从资源上取
     * @param view
     * @param currentPositionFrameResId
     */
    public void loadFrameThumbnail(ImageView view, int currentPositionFrameResId, int position){
        Bitmap b = mThumbnailBitmaps.get(FRAME_ID+currentPositionFrameResId);
        if(b != null){
            view.setBackgroundDrawable(new BitmapDrawable(b));
        } else{
            mThreadPool.submit(new FrameIconManager.IconRunnable(view, currentPositionFrameResId,position));
        }
    }

    class IconRunnable implements Runnable{

        private final WeakReference<ImageView> mImageViewReference;
        private Integer frame_id;
        private final int mPosition;

        public IconRunnable(ImageView view, int currentPositionFrameResId,int position){
            mImageViewReference = new WeakReference<ImageView>(view);
            frame_id = currentPositionFrameResId;
            mPosition = position;
        }

        @Override
        public void run() {
            try {
                ImageView collageBackgroundView = mImageViewReference.get();
                if (collageBackgroundView!=null&&collageBackgroundView.getTag().equals(mPosition)){//必须保证是同一个
                    Bitmap b = null;
                    Resources res = ComponentContext.getContext().getResources();
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    b = BitmapFactory.decodeResource(res, frame_id);
                    //获取大图略缩图,并对原图回收
                    Bitmap bitmapicon = ThumbnailUtils.extractThumbnail(b, widthOrHeight, widthOrHeight, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
                    if(bitmapicon != null) {
                        Message msg = Message.obtain(mHandler, MSG_END_RUNABLE);
                        msg.obj = new HandlerWithDatabean(bitmapicon,collageBackgroundView,frame_id,mPosition);
                        mHandler.sendMessage(msg);
                    }
                }


            } catch(Throwable e){

            }
        }
    }

    /**
     * 获取bitmap
     * @param res_id
     * @return
     */
    public Drawable getFrameDrawable( Resources resource,int res_id) {
        return  resource.getDrawable(res_id);
    }

    protected class HandlerWithDatabean{
        public Bitmap mBitmap;
        public ImageView frameView;
        public int mSrcframeID;
        public int position;

        public HandlerWithDatabean(Bitmap bitmap, ImageView frameView,int srcframeID,int position) {
            mBitmap = bitmap;
            this.frameView = frameView;
            this.mSrcframeID=srcframeID;
            this.position=position;
        }
    }


    /**
     * 一定要注意回收
     */
    public void onDestory(boolean isActfinish){
        try {
            if (isActfinish){
                mThreadPool.shutdownNow();
            }else{
//                mDrawales.clear();
                mThumbnailBitmaps.clear();
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
}
